let loginPromise = null; // 登录锁，全局唯一

const auth = (config) => {
    if (loginPromise) {
        return loginPromise; // 如果正在登录中，返回已有 promise
    }

    loginPromise = new Promise((resolve, reject) => {
        wx.login({
            success(res) {
                if (res.code) {
                    wx.request({
                        url: config.api[config.env].url + 'api/login/index',
                        method: 'POST',
                        data: { code: res.code, platform: 1 },
                        success(result) {
                            if (result.statusCode === 200 && result.data.data.token) {
                                const token = result.data.data.token;
                                wx.setStorageSync('share_user_id', result.data.data.user_info.id);
                                wx.setStorageSync('token', token);
                                resolve(token);
                            } else {
                                reject('登录失败：' + (result.data.msg || '未知错误'));
                            }
                        },
                        fail() {
                            reject('网络请求失败');
                        },
                        complete() {
                            loginPromise = null; // 无论成功失败，都清除锁，避免后续无法再发起
                        }
                    });
                } else {
                    loginPromise = null;
                    reject('wx.login 获取 code 失败');
                }
            },
            fail() {
                loginPromise = null;
                reject('wx.login 调用失败');
            }
        });
    });

    return loginPromise;
};

module.exports = {
    login: auth
};
